<template>
  <div>
    <a-row :gutter="[8, 8]">
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <!-- 客户模块 -->
        <a-card title="客户" :loading="customer.loading" :bordered="false" :body-style="{ padding: '6' }">
          <template #extra><a @click="loadData(customer)"><a-icon type="sync" /></a></template>
          <a-row>
            <template v-for="rec in customer.dataSource">
              <a-col :span="rec.width">
                <head-info :title="rec.label" :content="formatInt(rec.value)" :center="true" />
              </a-col>
            </template>
          </a-row>
        </a-card>

        <!-- 供应商模块 -->
        <a-card title="供应商" :loading="supplier.loading" :bordered="false" :body-style="{ padding: '6' }">
          <template #extra><a @click="loadData(supplier)"><a-icon type="sync" /></a></template>
          <a-row>
            <template v-for="rec in supplier.dataSource">
              <a-col :span="rec.width">
                <head-info :title="rec.label" :content="formatInt(rec.value)" :center="true" />
              </a-col>
            </template>
          </a-row>
        </a-card>
      </a-col>
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <!-- 消息通知模块 -->
        <a-card title="消息通知" :loading="notice.loading" :bordered="false" :body-style="{ padding: '0' }">
          <template #extra><a @click="loadData(notice)"><a-icon type="sync" /></a></template>
          <a-table :columns="noticeColumns" :data-source="notice.dataSource" :pagination="false"
            :row-key="record => record.id" :scroll="{ y: 240 }" :row-selection="rowSelection">
            <template #operation="text, record">
              <a-button type="primary" size="small" @click="markAsRead(record)" :disabled="record.finished === 1">
                {{ record.finished === 1 ? '已读' : '标记已读' }}
              </a-button>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[8, 8]">
      <!-- 利润明细柱状图 -->
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card title="利润明细" :loading="profitDetail.loading" :bordered="false" :body-style="{ padding: '0' }">
          <template #extra><a @click="loadData(profitDetail)"><a-icon type="sync" />查询</a></template>
          <bar :dataSource="profitDetail.dataSource" :height="300" style="padding: 0 8px 0 8px"
            :barConfig="profitDetailBarConfig" />
        </a-card>
      </a-col>

      <!-- 订单利润折线图 -->
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card :loading="profitTimeSeries.loading" :bordered="false" :body-style="{ padding: '0' }">
          <div style="display: flex; align-items: center; padding: 12px 16px; border-bottom: 1px solid #f0f0f0;">
            <div style="font-weight: 500; font-size: 16px; margin-right: 50px;">订单利润</div>
            <div style="display: flex; align-items: center; margin-right: 16px;">
              <span style="margin-right: 8px;">日期范围：</span>
              <j-date placeholder="请选择开始" style="width: 150px; margin-right: 8px;" v-model="beginDate"
                dateFormat="YYYY-MM-DD" />
              <span style="margin: 0 4px;">-</span>
              <j-date placeholder="请选择结束" style="width: 150px; margin-right: 16px;" v-model="endDate"
                dateFormat="YYYY-MM-DD" />
            </div>
            <a @click="loadData(profitTimeSeries)" style="white-space: nowrap;"><a-icon type="sync" />查询</a>
          </div>
          <area-chart-ty :dataSource="profitTimeSeries.dataSource" :height="300" style="padding: 0 8px 0 8px" y="金额" />
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[8, 8]" style="margin-top: 16px;">
      <!-- 财务概览 -->
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card :loading="financeSummary.loading" :bordered="false" :body-style="{ padding: '0', height: '380px' }">
          <div style="display: flex; align-items: center; padding: 12px 16px; border-bottom: 1px solid #f0f0f0;">
            <div style="font-weight: 500; font-size: 16px; margin-right: 50px;">其他支出</div>
            <div style="display: flex; align-items: center; margin-right: 16px;">
              <span style="margin-right: 8px;">日期范围：</span>
              <j-date placeholder="请选择开始" style="width: 150px; margin-right: 8px;" v-model="financeBeginDate"
                dateFormat="YYYY-MM-DD" />
              <span style="margin: 0 4px;">-</span>
              <j-date placeholder="请选择结束" style="width: 150px; margin-right: 16px;" v-model="financeEndDate"
                dateFormat="YYYY-MM-DD" />
            </div>
            <a @click="loadData(financeSummary)" style="white-space: nowrap;"><a-icon type="sync" />查询</a>
          </div>
          <div style="padding: 16px;">
            <a-row>
              <template v-if="financeSummary.dataSource && financeSummary.dataSource.length > 0">
                <a-col v-for="rec in financeSummary.dataSource" :key="rec.payType" :xl="12" :lg="12" :md="12" :sm="24"
                  :xs="24">
                  <a-card-grid style="width: 100%; text-align: center; padding: 24px 16px;" :bordered="true">
                    <h4 style="margin-bottom: 16px; color: #333; font-size: 16px;">{{ rec.payType_dictText }}</h4>
                    <div style="font-size: 20px; font-weight: bold; ">¥ {{ formatAmt(rec.amount) }}</div>
                  </a-card-grid>
                </a-col>
              </template>
              <template v-else>
                <div style="text-align: center; padding: 20px; color: #999;">
                  暂无数据
                </div>
              </template>
            </a-row>
          </div>
        </a-card>
      </a-col>

      <!-- 其他支出折线图 -->
      <a-col :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <a-card :loading="otherExpense.loading" :bordered="false" :body-style="{ padding: '0', height: '380px' }">
          <div style="display: flex; align-items: center; padding: 12px 16px; border-bottom: 1px solid #f0f0f0;">
            <div style="font-weight: 500; font-size: 16px; margin-right: 50px;">其他支出</div>
            <div style="display: flex; align-items: center; margin-right: 16px;">
              <span style="margin-right: 8px;">日期范围：</span>
              <j-date placeholder="请选择开始" style="width: 150px; margin-right: 8px;" v-model="beginDate"
                dateFormat="YYYY-MM-DD" />
              <span style="margin: 0 4px;">-</span>
              <j-date placeholder="请选择结束" style="width: 150px; margin-right: 16px;" v-model="endDate"
                dateFormat="YYYY-MM-DD" />
            </div>
            <a @click="loadData(otherExpense)" style="white-space: nowrap;"><a-icon type="sync" />查询</a>
          </div>
          <area-chart-ty :dataSource="otherExpense.dataSource" :height="300" style="padding: 0 8px 0 8px" y="金额" />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import Bar from '@/components/chart/Bar'
import AreaChartTy from '@/components/chart/AreaChartTy'
import HeadInfo from '@/components/tools/HeadInfo'
import XEUtils from "xe-utils";
import { getAction } from '@/api/manage';
import JDate from '@/components/jeecg/JDate';
import { MessageBox } from 'element-ui';
export default {
  name: "ProfitAnalysis",
  components: { Bar, AreaChartTy, HeadInfo, JDate },
  data() {
    return {
      // 查询参数
      monthQuery: '',
      beginDate: '',
      endDate: '',
      // 财务概览独立的日期范围
      financeBeginDate: '',
      financeEndDate: '',

      // 利润明细柱状图数据
      profitDetail: {
        loading: false,
        dataSource: []
      },

      // 利润明细柱状图配置
      profitDetailBarConfig: [
        { dataKey: 'totalPayAmount', name: '总支出', color: '#ff4d4f', unit: '元' },    // 红色系
        { dataKey: 'totalReceiveAmount', name: '总收入', color: '#52c41a', unit: '元' }, // 绿色系
        { dataKey: 'otherPayAmount', name: '其他支出', color: '#faad14', unit: '元' },   // 橙色系
        { dataKey: 'profit', name: '利润', color: '#1890ff', unit: '元' }                // 蓝色系
      ],

      // 利润时间序列折线图数据
      profitTimeSeries: {
        loading: false,
        dataSource: []
      },

      // 财务概览数据
      financeSummary: {
        loading: false,
        dataSource: []
      },
      // 客户模块数据
      customer: {
        url: '/wrapper/cgreport/getData/1580740609854935042',
        loading: false,
        dataSource: [],
      },

      // 供应商模块数据
      supplier: {
        url: '/wrapper/cgreport/getData/1580740795561938946',
        loading: false,
        dataSource: [],
      },

      // 消息通知数据
      notice: {
        url: '/wr/notice/myNotice',
        loading: false,
        dataSource: []
      },

      // 消息通知表格列配置
      noticeColumns: [
        {
          title: '序号',
          key: 'index',
          width: 60,
          customRender: (text, record, index) => index + 1
        },
        {
          title: '消息',
          key: 'title',
           align: "center",
          dataIndex: 'title',
          ellipsis: true
        },
        {
          title: '操作',
          key: 'operation',
          width: 100,
          scopedSlots: { customRender: 'operation' }
        }
      ],

      // 表格行选择配置
      rowSelection: {
        type: 'checkbox'
      },


      // 其他支出折线图数据
      otherExpense: {
        loading: false,
        dataSource: []
      },
      url: {
        profitDetail: '/wr/stat/order/profit/list',//利润明细
        profitTimeSeries: '/wr/stat/order/profit/series',//订单利润 时间序列
        financeSummary: '/wr/stat/pay/byType',//财务概览
        otherExpense: '/wr/stat/pay/series',//其他支出
      }
    }
  },

  created() {
    // 设置默认日期范围：当前年份的1月到当前月
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;

    // 开始日期：当前年份的1月1日
    this.beginDate = `${currentYear}-01-01`;
    this.financeBeginDate = `${currentYear}-01-01`;

    // 结束日期：当前月的最后一天
    const lastDayOfCurrentMonth = new Date(currentYear, currentMonth, 0).getDate();
    const formattedMonth = currentMonth.toString().padStart(2, '0');
    const formattedDay = lastDayOfCurrentMonth.toString().padStart(2, '0');
    this.endDate = `${currentYear}-${formattedMonth}-${formattedDay}`;
    this.financeEndDate = `${currentYear}-${formattedMonth}-${formattedDay}`;

    // 初始化加载数据
    this.loadData(this.customer);
    this.loadData(this.supplier);
    this.loadData(this.profitDetail);
    this.loadData(this.profitTimeSeries);
    this.loadData(this.financeSummary);
    this.loadData(this.otherExpense);
    this.loadData(this.notice);
  },

  methods: {
    formatAmt(amt) {
      return XEUtils.commafy(amt, { digits: 2 }).toString();
    },

    // 标记消息为已读
    markAsRead(record) {
       MessageBox.confirm('确定要标记此消息为已读吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用已读接口
        console.log('标记已读...', record.id);
        this.$http.get(`/wr/notice/readNotice?id=${record.id}`)
          .then(res => {
            if (res.success) {
              this.$message.success('标记成功');
              // 更新本地数据状态
              record.finished = 1;
            } else {
              this.$message.error(res.message || '标记失败');
            }
          })
          .catch(error => {
            console.error('标记已读失败:', error);
            this.$message.error('标记失败');
          });
           this.loadData(this.notice);
      }).catch(() => {
        // 取消操作
      });
    },

    formatInt(i) {
      return XEUtils.commafy(i, { digits: 0 }).toString();
    },
    loadData(data) {
      data.loading = true;
      console.log('data', data);

      // 根据不同的数据类型调用对应的接口
      let url = '';
      let params = {};

      if (data === this.profitDetail) {
        url = this.url.profitDetail;
      } else if (data === this.profitTimeSeries) {
        url = this.url.profitTimeSeries;
        // 使用beginDate和endDate作为参数
        if (this.beginDate) {
          params.beginDate = this.beginDate;
        }
        if (this.endDate) {
          params.endDate = this.endDate;
        }
      } else if (data === this.financeSummary) {
        url = this.url.financeSummary;
        // 使用独立的财务概览日期参数
        if (this.financeBeginDate) {
          params.beginDate = this.financeBeginDate;
        }
        if (this.financeEndDate) {
          params.endDate = this.financeEndDate;
        }
      } else if (data === this.otherExpense) {
        url = this.url.otherExpense;
        // 使用与订单利润相同的日期参数
        if (this.beginDate) {
          params.beginDate = this.beginDate;
        }
        if (this.endDate) {
          params.endDate = this.endDate;
        }
      } else if (data === this.customer || data === this.supplier) {
        console.log('获取客户和供应商数据', data.url);
        url = data.url;
        // 客户和供应商模块直接调用原始接口

      } else if (data === this.notice) {
        console.log('获取消息数据', data);
        url = data.url;
      }

      getAction(url, params).then(res => {
        if (res.success && res.result) {
          // 根据接口返回的数据格式设置数据源
          if (data === this.profitTimeSeries) {
            // 处理利润时间序列数据，将period和amount转换为柱状图所需格式
            // Bar组件需要'x'和'y'字段
            data.dataSource = res.result.map(item => ({
              x: item.period,  // 横轴字段
              y: item.amount,  // 纵轴字段
              // 保留原始字段以备需要
              period: item.period,
              amount: item.amount
            }));
          } else if (data === this.profitDetail) {
            // 处理利润明细数据，将billNo作为x轴，四个字段作为不同的y轴数据
            data.dataSource = res.result.map(item => ({
              x: item.billNo,  // 横轴使用单据编号
              totalPayAmount: item.totalPayAmount || 0,      // 总支出
              totalReceiveAmount: item.totalReceiveAmount || 0, // 总收入
              otherPayAmount: item.otherPayAmount || 0,      // 其他支出
              profit: item.profit || 0,                      // 利润
              // 保留原始字段以备需要
              orderId: item.orderId,
              billNo: item.billNo,
              billDate: item.billDate
            }));
          } else if (data === this.financeSummary) {
            // 处理财务概览数据
            data.dataSource = res.result;
          } else if (data === this.otherExpense) {
            // 处理其他支出时间序列数据，格式化为图表所需格式
            data.dataSource = res.result.map(item => ({
              x: item.period,  // 横轴字段
              y: item.amount,  // 纵轴字段
              // 保留原始字段
              period: item.period,
              amount: item.amount
            }));
          } else if (data === this.customer || data === this.supplier) {
            data.dataSource = res.result.records || [];
          } else if (data === this.notice) {
            data.dataSource = res.result || [];
          } else {
            // 其他数据类型保持原样
            data.dataSource = res.result;
          }
        }
      }).catch(error => {
        console.error('请求失败:', error);
        this.$message.error('获取数据失败');
      }).finally(() => {
        data.loading = false;
      });
    },

    // 日期变化时重新加载数据
    handleDateChange() {
      this.loadData(this.profitTimeSeries);
    },



    formatAmt(amt) {
      return XEUtils.commafy(amt, { digits: 2 }).toString();
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-grid {
  width: 100%;
}
</style>